﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IDAL;
using Model;

namespace DAL
{
    public class D_CustomDetails : IDAL.ICustomDetails
    {
        WishDayEntities _e;
        public D_CustomDetails() {
            _e = new WishDayEntities();
        }
        public void Add(CustomDetails obj)
        {
            _e.CustomDetails.Add(obj);
            _e.SaveChanges();
        }

        public void Delete(int id)
        {
            var data= _e.CustomDetails.Find(id);
            _e.CustomDetails.Remove(data);
            _e.SaveChanges();
        }

        public CustomDetails FindById(int id)
        {
            return _e.CustomDetails.Find(id);
        }

        public List<CustomDetails> GetAll()
        {
            return _e.CustomDetails.ToList();
        }

        public List<Param_Custom> GetDataByTemplate(int id)
        {
            var details = _e.CustomDetails.AsEnumerable();
            var type = _e.CustomType.AsEnumerable();
            var data = from cd in details
                       join ct in type on cd.CTypeID equals ct.CTypeID
                       where cd.TemplateID == id
                       orderby ct.CPower ascending
                       group cd by ct into g
                       select new Param_Custom
                       {
                           CTypeID = g.Key.CTypeID,
                           CName = g.Key.CName,
                           CPower = g.Key.CPower,
                           IsShow = g.Key.IsShow,
                           ListCustomDetails = (from gg in g
                                                select new Param_CustomDetails
                                                {
                                                    CDetailsID = gg.CDetailsID,
                                                    CDTitle = gg.CDTitle,
                                                    CTitleGrade = gg.CTitleGrade,
                                                    CDDescribe = gg.CDDescribe,
                                                    IsOnTrue = gg.IsOnTrue,
                                                    CTypeID = gg.CTypeID,
                                                    TemplateID = gg.TemplateID
                                                }).ToList()
                       };
            return data.ToList();
        }

        public void Update(int id, CustomDetails obj)
        {
            var data = _e.CustomDetails.Find(id);
            data.CDTitle = obj.CDTitle;
            data.CTitleGrade = obj.CTitleGrade;
            data.CDDescribe = obj.CDDescribe;
            data.IsOnTrue = obj.IsOnTrue;
            data.CTypeID = obj.CTypeID;
            data.TemplateID = obj.TemplateID;
            _e.SaveChanges();
        }
    }
}
